package edu.nuist.app.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.nuist.app.entity.LoginUser;
import edu.nuist.app.entity.User;
import edu.nuist.app.enums.CustomExceptionType;
import edu.nuist.app.exception.CustomException;
import edu.nuist.app.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author wangzhuangzhuang
 * @DESC:
 * @date 2022-04-03 20:43
 */

@Component
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private UserMapper userMapper;

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 查询用户信息
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(User::getUserName, username);
		User user = userMapper.selectOne(queryWrapper);
		// 如果没有查询到用户就抛出异常
		if(ObjectUtil.isNotNull(user)){
			throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "用户不存在");
		}
		// TODO 查询对应的权限信息

		// 把数据封装成UserDetails返回
		return new LoginUser(user);
	}
}